<?php

namespace app\admin\controller\users;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;

/**
 * 用户列表
 *
 * @icon fa fa-user
 */
class Users extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Users;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["level"=>['id','level_name'],"card"=>['id','name']])
                ->with([
                    'level' => function ($query) {
                        $query->withField('id,level_name');
                    },
                    'card' => function ($query) {
                        $query->withField('id,name');
                    },
                ])
                ->where($where)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $list->items()[$k]->count = Db::table('fa_info')
                        ->where('user_id',$v->id)
                        ->count();

                    $ni = Db::table('fa_users')
                        ->where('id',$v->invite)
                        ->find();

                    $pid = Db::table('fa_users')
                        ->where('id',$v->pid)
                        ->find();

                    if (empty($pid)){
                        $list->items()[$k]->pid_name = '';
                    }else{
                        $list->items()[$k]->pid_name = $pid['nickname'];
                    }

                    if (empty($ni)){
                        $list->items()[$k]->family = '';
                    }else{
                        $list->items()[$k]->family = $v->invite.'/'.$ni['nickname'];
                    }
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row->create_time = date('Y-m-d H:i:s',$row->create_time);
        $row->login_time = date('Y-m-d H:i:s',$row->login_time);
        $row->vip_time = empty($row->vip_time) ? '':$row->vip_time;
        $row->vip_time = empty($row->vip_time) ? '':$row->vip_time;

        $vip_name = Db::table('fa_vip_level')
            ->where('id',$row->level)
            ->find();

        $vip_card = Db::table('fa_vip_card')
            ->where('id',$row->vip)
            ->find();

        $family = Db::table('fa_users')
            ->where('id',$row->invite)
            ->find();

        $pid = Db::table('fa_users')
            ->where('id',$row->pid)
            ->find();

        if (empty($pid)){
            $pid_name = '';
        }else{
            $pid_name = $pid['nickname'];
        }

        if (empty($family)){
            $family_name = '';
        }else{
            $family_name = $family['id'].'/'.$family['nickname'];
        }

        $this->view->assign("row", $row);
        $this->view->assign("vip_name", $vip_name);
        $this->view->assign("vip_card", $vip_card);
        $this->view->assign("family_name", $family_name);
        $this->view->assign("pid_name", $pid_name);
        return $this->view->fetch();
    }

    /**
     * 会员等级下拉查询
     *
     */
    public function source(){
        $list = [];
        //$json = cache('source');
        //if ($json===false){
            $lists = Db::table('fa_vip_level')
                ->field('id,level_name')
                ->select();

            if (!empty($lists)){
                foreach ($lists as $k=>$v){
                    $list[] = $v['level_name'];
                }
            }


            $json = json($list);
            //cache('source',$json);
        //}

        return $json;

    }

    /**
     * 会员卡等级下拉查询
     *
     */
    public function sources(){
        $list = [];
        //$json = cache('source');
        //if ($json===false){
        $lists = Db::table('fa_vip_card')
            ->field('id,name')
            ->select();

        if (!empty($lists)){
            foreach ($lists as $k=>$v){
                $list[] = $v['name'];
            }
        }


        $json = json($list);
        //cache('source',$json);
        //}

        return $json;

    }

    /**
     * 升级会员卡
     * @param $ids
     * @return string
     * @throws \think\Exception
     *
     */
    public function edits($ids){

        $row = Db::table('fa_users')
            ->where('id',$ids)
            ->find();

        $rows = Db::table('fa_vip_card')
            ->select();
        $rows[] = [
            'id' => 0,
            'name' => '无',
        ];
        $this->view->assign("row", $row);
        $this->view->assign("rows", $rows);
        return $this->view->fetch();
    }

    /**
     * 发货操作
     *
     */
    public function editss(){
        $arr = request()->param();

        $data = Db::table('fa_users')
            ->where('id',$arr['id'])
            ->find();

        if (empty($data)){
            $this->error('用户数据为空');
        }


        //事务开启
        Db::startTrans();
        $update = Db::table('fa_users')
            ->where('id',$arr['id'])
            ->update([
                'vip' => $arr['vip'],
                'update_time' => time(),
            ]);

        $updates = Db::table('fa_users')
            ->where('pid',$arr['id'])
            ->update([
                'vip' => $arr['vip'],
                'update_time' => time(),
            ]);


        if (($update !== false) && ($updates !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }


    }

}
